package com.csun.dsms.controller;

import com.csun.dsms.comment.base.constant.GlobalConstant;
import com.csun.dsms.comment.core.annotation.Authorization;
import com.csun.dsms.comment.core.annotation.CurrentUser;
import com.csun.dsms.comment.core.annotation.LogAnnotation;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.model.domain.DsmsUser;
import com.csun.dsms.model.entity.TokenModel;
import com.csun.dsms.service.DsmsUserService;
import com.csun.dsms.service.TokenManager;
import com.csun.dsms.utils.RedisUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @desc    用户登录拦截器
 */
@RestController
@RequestMapping("/login")
public class TokenController {

    @Resource
    private DsmsUserService dsmsUserService;
    @Resource
    private TokenManager tokenManager;
    @Resource
    private RedisUtil redisUtil;

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    public Wrapper login(@RequestParam String username,
                            @RequestParam String password,
                            HttpServletRequest request)throws Throwable{

        DsmsUser user =  dsmsUserService.login(username, password);
        //生成一个token，保存用户登录状态
        TokenModel model = tokenManager.get(user.getId());
        if (model == null) {
            model = tokenManager.createToken(user.getId());
        }

        // 存储user
        String token = model.getUserId() + "_" + model.getToken();
        redisUtil.set(token, user, GlobalConstant.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);

        return WrapMapper.ok(model);
    }

    /**
     * 第三方登录获取用户信息
     */


    /**
     * 注销
     */
    @Authorization
    @RequestMapping(method = RequestMethod.DELETE)
    public Wrapper logout(@CurrentUser DsmsUser user) {

        tokenManager.deleteToken(user.getId());

        return WrapMapper.ok();
    }


}
